package cn.bbstone.pisces2.client.handler;

import cn.bbstone.pisces2.client.base.ClientCache;
import cn.bbstone.pisces2.client.task.impl.FileTask;
import cn.bbstone.pisces2.client.task.impl.ListTaskListener;
import cn.bbstone.pisces2.client.util.MsgUtil;
import cn.bbstone.pisces2.comm.BFileCmd;
import cn.bbstone.pisces2.comm.recv.RspFileInfo;
import cn.bbstone.pisces2.proto.rsp.RspFile;
import cn.bbstone.pisces2.util.BByteUtil;
import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RspListInfoHandler implements ClientHandler {
    private static Logger log = LoggerFactory.getLogger(RspListInfoHandler.class);

    public RspListInfoHandler() {
    }

    @Override
    public void handle(ChannelHandlerContext channelHandlerContext, RspFile rspFile) {
    	RspFileInfo rspFileInfo = new RspFileInfo();
    	rspFileInfo.setMsgId(rspFile.getMsgId());
    	rspFileInfo.setMsgType(rspFile.getMsgType());
    	rspFileInfo.setFileNo(rspFile.getFileNo());
    	rspFileInfo.setChunks(rspFile.getChunks());
    	rspFileInfo.setChecksum(BByteUtil.toStr(rspFile.getBodyData())); // file checksum, not body checksum
    	log.debug("rsp file info: {}", JSONUtil.toJsonStr(rspFileInfo));
    	
//        String msgId = rspFile.getMsgId();
//        Byte msgType = rspFile.getMsgType();
        long fileNo = rspFile.getFileNo();
//        long chunkNo = rspFile.getChunkNo();
//        String fileChecksum = BByteUtil.toStr(rspFile.getBodyData());
//        log.debug("msg id: {}, msgType: {}, fileNo: {}, chunkNo: {}, file checksum: {}",
//                msgId, msgType, fileNo, chunkNo, fileChecksum);
        //
        FileTask fileTask = ClientCache.getTask(fileNo);
        if (fileTask == null) {
            // save fli.idx file info
//            RspFile rspFile = (RspFile)rspListInfo;
            fileTask = new FileTask(rspFileInfo);
            ClientCache.addTask(fileNo, fileTask);
            fileTask.addListner(new ListTaskListener());
            log.debug("create fileTask for fileNo: {}, chunks: {}", fileNo, rspFile.getChunks());
            // send REQ_LIST_DATA request
            handleNext(channelHandlerContext, rspFile, fileTask);
        } else {
        	log.info("===============================================");
        	log.error("[LIST INFO] already exists task for fileNo: {}", fileNo);
        	log.info("===============================================");
        }

    }

    @Override
    public void handleNext(ChannelHandlerContext ctx, RspFile rspFile, FileTask fileTask) {
        // send REQ_LIST_DATA request
        log.debug("send first file data chunk request for fileNo: {}", rspFile.getFileNo());
        ByteBuf reqIndexData = MsgUtil.buildReq(BFileCmd.REQ_LIST_DATA, 0L);
        ctx.writeAndFlush(reqIndexData);
    }
}
